package com.netx.cubigraf.apps.utilities;
import java.io.IOException;
import com.netx.generics.io.BufferedWriter;
import com.netx.generics.io.Directory;
import com.netx.generics.io.File;
import com.netx.generics.io.FileSystem;
import com.netx.generics.io.Location;
import com.netx.generics.sql.Row;
import com.netx.generics.sql.Table;
import com.netx.generics.time.Date;
import com.netx.generics.util.Strings;
import com.netx.generics.translation.Results;
import com.netx.cubigraf.entities.Referencia;
import com.netx.cubigraf.shared.Zipper;
import com.netx.data.Connection;
import com.netx.data.Database;
import com.netx.data.DatabaseException;


public class PRJ10_Unzipper {

	public static void run() throws Throwable {
		//FileSystem servidor = new FileSystem("fs://localhost/servidordados");
		//FileSystem dest = new FileSystem("fs://localhost/[C]/Shared/04.Dev/03.Applications/Java/03.Test/Unzipped");
		FileSystem servidor = new FileSystem(new Location("//servidordados/ROOT"));
		FileSystem dest = new FileSystem(new Location("//servidordados/ROOT/Temp"));
		PRJ10_Unzipper unzipper = new PRJ10_Unzipper(servidor, dest);
		unzipper.unzip();
	}
	
	// INSTANCE:
	private final Directory _servidor;
	private final Directory _dest;
	private final File _csv;
	
	public PRJ10_Unzipper(Directory servidor, Directory dest) throws IOException {
		_servidor = servidor;
		_dest = dest;
		File csv = dest.getFile("results.csv");
		if(csv != null) {
			csv.delete();
		}
		_csv = dest.createFile("results.csv");
	}
	
	public void unzip() throws IOException, DatabaseException {
		Directory ficheiros = _servidor.getDirectory("/Ficheiros");
		Directory zips = _servidor.getDirectory("/Zips");
		// ir buscar o ficheiro database.xml:
		Results r = Database.init(getClass().getResourceAsStream("PRJ10_database.xml"));
		Database database = (Database)r.getContents();
		if(r.hasErrors()) {
			System.out.println("errors initializing database...");
			return;
		}
		Connection c = database.getConnection();
		Table result = c.select("s.cdg_servico, s.referencia, s.data_abertura, u.name FROM servicos s INNER JOIN users u ON s.cdg_desenhador=u.user_code WHERE s.cdg_servico<=29465 AND s.estado<>'a' ORDER BY s.cdg_servico");

		Referencia ref = null;
		BufferedWriter writer = new BufferedWriter(_csv.getOutputStream());
		for(int i=0; i<result.getRowCount(); i++) {
			Row row = result.getRow(i);
			Date dataAbertura = row.getDate(3);
			ref = new Referencia(dataAbertura, row.getInt(2));
			String path = dataAbertura.getYear()+"/"+Strings.valueOf(dataAbertura.getMonth(), 2)+"/"+ref.toString();
			if(ficheiros.getDirectory(path) == null) {
				File zip = zips.getFile(path+".zip");
				if(zip == null) {
					System.out.println("Reference '"+ref.toString()+"' wasn't found anywhere!");
					writer.write(ref.toString()+"\n\r");
					writer.flush();
				}
				else {
					System.out.print("Unzipping '"+ref.toString()+"'...");
					try {
						Zipper.unzip(zip, _dest);
					}
					catch(IOException io) {
						System.out.print(" error: " + io);
						writer.write(ref.toString()+";"+io+"\n\r");
						writer.flush();
					}
					System.out.println();
				}
			}
		}
		writer.close();
		c.close();
	}
	
}
